package com.party.mobile.biz.order.payOrder;

import com.party.common.constant.Constant;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.DateUtils;
import com.party.core.model.activity.Activity;
import com.party.core.model.crowdfund.*;
import com.party.core.model.message.MessageOutput;
import com.party.core.model.order.OrderType;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.crowdfund.IEventGradationService;
import com.party.core.service.crowdfund.IProjectGradationService;
import com.party.core.service.crowdfund.IProjectInfoGradationService;
import com.party.core.service.crowdfund.IProjectService;
import org.apache.tools.ant.BuildException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created by wei.li
 * on 2019/4/17
 */

@Service
public class PayOrderFactory {

    @Resource(name = "activityPayOrderService")
    private IPayOrderService activityPayOrderService;

    @Resource(name = "coursePayOrderService")
    private IPayOrderService coursePayOrderService;

    @Resource(name = "crowdfundPayOrderService")
    private IPayOrderService crowdfundPayOrderService;

    @Resource(name = "mallPayOrderService")
    private IPayOrderService mallPayOrderService;

    @Resource(name = "crowdfundMultiPayOrderService")
    private IPayOrderService CrowdfundMultiPayOrderService;

    @Autowired
    private IProjectInfoGradationService projectInfoGradationService;
    @Autowired
    private IProjectGradationService projectGradationService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private IEventGradationService eventGradationService;

    public IPayOrderService buildPayOrder(Integer orderType) {

        if (OrderType.ORDER_ACTIVITY.getCode().equals(orderType)) {
            return activityPayOrderService;
        } else if (OrderType.ORDER_COURSE.getCode().equals(orderType)) {
            return coursePayOrderService;
        } else if (OrderType.ORDER_CROWD_FUND.getCode().equals(orderType)) {
            return crowdfundPayOrderService;
        } else if (OrderType.ORDER_MALL.getCode().equals(orderType)) {
            return mallPayOrderService;
        }else if (OrderType.ORDER_MULTIPLE_CROWD_FUND.getCode().equals(orderType)) {
            return CrowdfundMultiPayOrderService;
        } else {
            throw new BuildException("订单类型错误");
        }
    }

    /***不需要推送海报，不需要推送报名
     * 多场活动自动转入下个阶段/定时器，个人众筹页 维护zc_project_info,zc_project_gradation
     * @param ongoingGradation  系统时间阶段
     * @param project
     */
    public void automaticShift(EventGradation ongoingGradation, Project project, Activity activity) {
        int type = 0;//默认阶段没有成功
        ProjectInfoGradation byProjectId = projectInfoGradationService.findByProjectId(project.getId());
        ProjectGradation ongoingProjectGradation = projectGradationService.getByEventGradationId(ongoingGradation.getId(), project.getId());
        /** 找到当前系统阶段之前所有成功阶段的目标金额之和*/
        Double effectiveAmount = projectGradationService.getEffectiveAmount(ongoingGradation.getEndTime(), project.getId());
        /** 累计金额减去前面阶段的众筹成功金额等于剩余金额*/
        double surplus = BigDecimalUtils.sub(project.getActualAmount().doubleValue(), effectiveAmount);
        surplus = BigDecimalUtils.round(surplus, 2);
        /** 如果剩余金额大于等于当前系统阶段的目标金额，那说明当前阶段已经成功了*/
        if (surplus >= ongoingProjectGradation.getTargetAmount()){
            if (effectiveAmount < 0.01) {
                // 商品正在众筹人数减
                activity.setCrowdfundedNum(activity.getCrowdfundedNum() + 1);
                Integer beCrowdfundNum = activity.getBeCrowdfundNum() - 1 <= 0 ? 0 : activity.getBeCrowdfundNum() - 1;
                activity.setBeCrowdfundNum(beCrowdfundNum);
                activity.setSalesNum(activity.getSalesNum() + 1);
            }
            type = 1;//阶段成功了
            //获取当前系统阶段之后的阶段
            List<ProjectGradation> projectGradationList = projectGradationService.getAfterProjectGradations(ongoingGradation, project.getId());
            //目标金额
            double targetMoney = ongoingProjectGradation.getTargetAmount();
            if (projectGradationList.size() > 0) {
                for (ProjectGradation projectGradation : projectGradationList) {
                    byProjectId.setProjectGradationId(projectGradation.getId());
                    projectInfoGradationService.update(byProjectId);
                    this.updateProjectGradation(ongoingProjectGradation, project, type);

                    targetMoney = BigDecimalUtils.add(targetMoney, projectGradation.getTargetAmount());
                    targetMoney = BigDecimalUtils.round(targetMoney, 2);
                    double round = BigDecimalUtils.round(BigDecimalUtils.sub(surplus, targetMoney), 2);
                    if (round < 0) {
                        break;
                    }
                    /** 如果最后一个阶段都筹满了 那update最后一个阶段的project_gradation*/
                    ProjectGradation projectGradation1 = projectGradationList.get(projectGradationList.size() - 1);
                    if (projectGradation.getId().equals(projectGradation1.getId())) {
                        this.updateProjectGradation(projectGradation, project, type);
                        project.setIsSuccess(Constant.IS_SUCCESS);
                        activity.setSalesNum(activity.getSalesNum() + 1);
                    }
                    ongoingProjectGradation = projectGradation;
                }
            }else {
                /** 说明是最后一场成功了*/
                this.updateProjectGradation(ongoingProjectGradation, project, type);
                project.setIsSuccess(Constant.IS_SUCCESS);
                activity.setSalesNum(activity.getSalesNum() + 1);
            }

        }else {
            byProjectId.setProjectGradationId(ongoingProjectGradation.getId());
            projectInfoGradationService.update(byProjectId);
            //阶段未筹满  改ProjectGradation 中的useTime
            this.updateProjectGradation(ongoingProjectGradation, project, type);
        }
        projectService.update(project);
        activityService.update(activity);
    }

    /**
     * @Author hzq
     * @Description //阶段众筹  维护project_gradation中的useTime字段
     * @Date 19:14 2019/4/18
     * @param ongoingProjectGradation
     * @param project
     * @param type
     * @return
     **/
    public void updateProjectGradation(ProjectGradation ongoingProjectGradation, Project project,
                                        int type) {

        //根据当前阶段找到上一阶段
        ProjectGradation projectGradationOnA = projectGradationService.
                getTheNextGradation(ongoingProjectGradation);
        long now = DateUtils.getTodayDate().getTime();
        if (projectGradationOnA == null) {
            long createDate = project.getCreateDate().getTime();
            ongoingProjectGradation.setUseTime(now - createDate);
        } else {
            long createDate;
            if("1970-01-01".equals(DateUtils.formatDate(projectGradationOnA.getSuccessTime()))){
                //如果上个阶段没有成功
                EventGradation eventGradation = eventGradationService.get(projectGradationOnA.getEventGradationId());
                createDate = eventGradation.getEndTime().getTime();
            }else {
                createDate = projectGradationOnA.getSuccessTime().getTime();
            }
            long useTime = now - createDate;
            if(type == 1){
                ongoingProjectGradation.setSuccessTime(new Date());
                if(useTime <= 0){
                    useTime = 6000;
                }
            }
            ongoingProjectGradation.setUseTime(useTime);
        }
        projectGradationService.update(ongoingProjectGradation);
    }
}
